package com.zwh.dianzong;


import java.math.BigInteger;

/**
 * @author zwh
 * @date 2023-9-7 14:54
 */
public class HexUtils {

    public static  String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
    public static byte[] hexStringToBytes(String src) {
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            ret[i] = (byte) Integer.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
        }
        return ret;
    }
    /**
     * hex转换为浮点型
     * @param hexStr
     * @return
     */
    public static float castToFloat(String hexStr) {
        return Float.intBitsToFloat(new BigInteger(hexStr, 16).intValue());
    }
    /**
     * 将十六进制表示的ASCII字符串，转化成ASCII字符对应的十六进制，比如ASCII字符 '1' ==> 十六进制 31
     * @param hexAscii
     * @return
     */
    public static String hexAsciiToHexString(char[] hexAscii) {
        StringBuilder hexString = new StringBuilder();
        String sTemp;
        for (char c : hexAscii) {
            sTemp = Integer.toHexString((int) c);
            if (sTemp.length() < 2) {
                hexString.append(0);
            }
            hexString.append(sTemp.toUpperCase());
        }
        return hexString.toString();
    }
    /**
     * 十六进制字符串，转到对应ASCII字符
     * 比如 31 ==》  ASCII字符为：'1'
     * @param hexStr 十六进制字符串
     * @return
     */
    public static String hexStringToHexAscii(String hexStr) {
        int offset = 2;
        StringBuilder hexAscii = new StringBuilder();
        for (int i = 0; i < hexStr.length(); i += offset) {
            String str = hexStr.substring(i, i + offset);
            hexAscii.append((char) Integer.parseInt(str, 16));
        }
        return hexAscii.toString();
    }
}
